package server;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

public class Server
{

    public Server() throws IOException
    {
        InetSocketAddress address = new InetSocketAddress("localhost", 8000);
        HttpServer httpServer = HttpServer.create(address, 10);
        httpServer.createContext("/", new Handler());
        httpServer.setExecutor(Executors.newFixedThreadPool(10));
        httpServer.start();
        System.out.println("Server started\nPress any key to stop...");
        System.in.read();
        httpServer.stop(0);
        System.out.println("Server stoped");

    }

    
    class Handler implements HttpHandler
    {
        @Override
        public void handle(HttpExchange t) throws IOException
        {
            String request = getRequest(t);                                    
            System.out.println(request);
            sendResponse(t,"California calling!");                        
        }
    }

    public String getRequest(HttpExchange t)
    {
        String ret = null;
        try
        {            
            InputStream is = t.getRequestBody();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            ret = rd.readLine();
        } catch (IOException ex)
        {
            ex.printStackTrace();
        }
        return ret;
    }

    public void sendResponse(HttpExchange t, String resp)
    {
        try
        {
            StringBuilder response = new StringBuilder().append(resp);
            t.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length());
            t.getResponseBody().write(response.toString().getBytes());
            t.getResponseBody().close();
            t.close();
        } catch (IOException ex)
        {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args)
    {
        try
        {
            new Server();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
